package com.socool.sinofaith.ui;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import net.tsz.afinal.FinalBitmap;
import net.tsz.afinal.FinalHttp;
import net.tsz.afinal.http.AjaxCallBack;
import net.tsz.afinal.http.AjaxParams;

import android.app.Dialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils.TruncateAt;
import android.util.Log;
import android.view.Display;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

import com.deying.actionbarcompat.ActionBarHelperBase;
import com.deying.actionbarcompat.ActionBarHelperBase.CenterViewFactory;
import com.deying.actionbarcompat.ActionBarHelperBase.SpinnerViewFactory;
import com.socool.sinofaith.R;
import com.socool.sinofaith.SocoolApplication;
import com.socool.sinofaith.dao.QuestionAnswerDao;
import com.socool.sinofaith.dao.SifTaskDao;
import com.socool.sinofaith.dao.SifTaskQuestionDao;
import com.socool.sinofaith.jsonparse.HttpJsonAdapter;
import com.socool.sinofaith.model.QuestionAnswerBean;
import com.socool.sinofaith.model.SifQuestionOptionsBean;
import com.socool.sinofaith.model.SifTaskBean;
import com.socool.sinofaith.model.SifTaskQuestionBean;
import com.socool.sinofaith.model.ViewAnswerBean;
import com.socool.sinofaith.model.ViewQuestionBean;
import com.socool.sinofaith.model.ViewAnswerBean.ViewAnswer;
import com.socool.sinofaith.model.ViewAnswerBean.ViewAnswer.AVI;
import com.socool.sinofaith.model.ViewQuestionBean.Question;
import com.socool.sinofaith.model.ViewQuestionBean.Question.Option;
import com.socool.sinofaith.ui.AnswerQuestionActivity.ItemClickListener;
import com.socool.sinofaith.util.ConstansJsonUrl;
import com.socool.sinofaith.util.SinofaithUtil;
import com.socool.sinofaith.view.MyDialog;
import com.socool.sinofaith.view.MyGridView;

public class QuestionDetailActivity extends BaseActivity implements
		CenterViewFactory, SpinnerViewFactory {
	ActionBarHelperBase mActionBarHelperBase;

	private LinearLayout linearLayout;

	private SifTaskQuestionDao questionDao;
	private SifTaskQuestionBean taskQuestionBean;
	private SifTaskBean taskBean;

	private ArrayList<SifTaskQuestionBean> questionBeans;

	private ArrayList<QuestionAnswerBean> answerlist;
	private ArrayList<ViewAnswer> netAnswerList;

	private String Task_Name, taskid, Template_ID, type, Answer_ID, SubTask_ID,
			Stemp_ID,netType;

	QuestionAnswerDao answerDao;

	private ContentResolver mContentResolver;
	final int IMAGE_MAX_SIZE = 1024;

	MyGridView gridView;
	ArrayList<HashMap<String, Object>> lstImageItem = new ArrayList<HashMap<String, Object>>();
	
	MediaPlayer player = new MediaPlayer();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_questiondetail);
		SocoolApplication.addActivity(this);
		mActionBarHelperBase = (ActionBarHelperBase) this.getActionBarHelper();
		mActionBarHelperBase.setmCenterViewFactory(this);
		mActionBarHelperBase.setmSpinnerViewFactory(this);

		mContentResolver = getContentResolver();

		linearLayout = (LinearLayout) findViewById(R.id.prarms_layout);
		answerDao = new QuestionAnswerDao(this);
		questionDao = new SifTaskQuestionDao(this);
		SifTaskDao taskDao = new SifTaskDao(this);

		type = getIntent().getStringExtra("type");
		if ("1".equals(type)) {
			taskid = getIntent().getStringExtra("taskid");
			answerlist = (ArrayList<QuestionAnswerBean>) getIntent()
					.getSerializableExtra("answerlist");
			Template_ID = getIntent().getStringExtra("Template_ID");
			createOptions();
		} else {
			Answer_ID = getIntent().getStringExtra("Answer_ID");
			taskid = getIntent().getStringExtra("taskid");
			SubTask_ID = getIntent().getStringExtra("SubTask_ID");
			Stemp_ID = getIntent().getStringExtra("Stemp_ID");
			Template_ID = getIntent().getStringExtra("Template_ID");
			netAnswerList = new ArrayList<ViewAnswer>();
			answerlist = new ArrayList<QuestionAnswerBean>();

			String sql = "select * from " + QuestionAnswerBean.TABLENAME
					+ " where Task_ID=" + taskid + " and SubTask_ID="
					+ SubTask_ID;
			if (null != Stemp_ID && !"".equals(Stemp_ID)) {
				sql += " and Stemp_ID=" + Stemp_ID;
			}
			sql += " and Submiter=" + getSPString();
			answerlist = answerDao.queryBySql(sql);
			// answerlist = answerDao.queryBySql("select * from "
			// + QuestionAnswerBean.TABLENAME + " where Task_ID='"
			// + taskid + "' and SubTask_ID='" + SubTask_ID
			// + "' and Stemp_ID='" + Stemp_ID + "' and Submiter='"
			// + SinofaithUtil.userInfo.getUserMobile() + "'");
			if (null != answerlist && answerlist.size() > 0) {
				createOptions();
			} else {
				getViewAnswer();
			}
		}

		List<SifTaskBean> tasklist = taskDao.queryBySql("select * from "
				+ SifTaskBean.TABLENAME + " where Task_ID='" + taskid + "'");
		Task_Name = getIntent().getStringExtra("taskName");
//		if (null != tasklist && tasklist.size() > 0) {
//			taskBean = tasklist.get(0);
//			Task_Name = taskBean.getTaskName();
//		}
		

		// Toast.makeText(this, answerlist+"", Toast.LENGTH_LONG).show();

		lstImageItem = new ArrayList<HashMap<String, Object>>();
		gridView = new MyGridView(this, null);
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	void getViewAnswer() {
		FinalHttp fh = new FinalHttp();
		AjaxParams params = new AjaxParams();
		params.put("sid", ConstansJsonUrl.viewAnswer_url);
		params.put("did", SinofaithUtil.did);
		params.put("answerid", Answer_ID);
		Log.v("qqqq", ConstansJsonUrl.REQUEST_URL + "?" + params);
		fh.get(ConstansJsonUrl.REQUEST_URL, params, new AjaxCallBack() {

			@Override
			public void onStart() {
				super.onStart();
			}

			@Override
			public void onLoading(long count, long current) {
				// TODO Auto-generated method stub
				super.onLoading(count, current);
			}

			@Override
			public void onSuccess(Object t) {
				Log.v("qqqq", t.toString());
				super.onSuccess(t);
				try {
					ViewAnswerBean viewAnswerBean = HttpJsonAdapter
							.getInstance().get(t.toString(),
									ViewAnswerBean.class);
					if (viewAnswerBean.getResult().equals("0")) {
						if (null != viewAnswerBean.getAnswerList()
								&& viewAnswerBean.getAnswerList().size() > 0) {
							netAnswerList = viewAnswerBean.getAnswerList();
							// for(int
							// i=0;i<viewAnswerBean.getAnswerList().size();i++){
							// ViewAnswer
							// viewAnswer=viewAnswerBean.getAnswerList().get(i);
							// QuestionAnswerBean answerBean=new
							// QuestionAnswerBean();
							// answerBean.setAnswer(viewAnswer.getAnswer());
							// answerBean.setAnswerType(viewAnswer.getQuestionType());
							// answerBean.setFileCount(viewAnswer.getFilesCount());
							// answerBean.setOtherAnswer(viewAnswer.getOtherAnswer());
							// answerBean.setTaskQuestion_ID(viewAnswer.getTaskQuestion_ID());
							// answerlist.add(answerBean);
							// }

							createOptions();
						}

					} else {
						Toast.makeText(QuestionDetailActivity.this,
								viewAnswerBean.getDesc(), Toast.LENGTH_LONG)
								.show();
						QuestionDetailActivity.this.finish();
					}
				} catch (Exception e) {
					Toast.makeText(QuestionDetailActivity.this, e.getMessage(),
							Toast.LENGTH_LONG).show();
					QuestionDetailActivity.this.finish();
				}

			}

			@Override
			public void onFailure(Throwable t, int errorNo, String strMsg) {
				// TODO Auto-generated method stub
				super.onFailure(t, errorNo, strMsg);
				Toast.makeText(QuestionDetailActivity.this, strMsg,
						Toast.LENGTH_LONG).show();
			}

		});
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater menuInflater = getMenuInflater();
		menuInflater.inflate(R.menu.common, menu);
		return super.onCreateOptionsMenu(menu);
	}

	public View createView() {
		TextView tv = new TextView(this);
		tv.setText(Task_Name);
		tv.setTextColor(this.getResources().getColor(R.color.white));
		tv.setTextSize(20);
		tv.setSingleLine(true);
		tv.setMaxEms(10);
		tv.setEllipsize(TruncateAt.END);
		return tv;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) { // TODO Auto-generated
															// method stub
		if (item.getItemId() == R.id.home) {
			finish();
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public View createSpinnerView() {
		ImageView imageview = new ImageView(this);
		return imageview;
	}

	Uri originalUri;

	void createOptions() {

		LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
				LinearLayout.LayoutParams.FILL_PARENT,
				LinearLayout.LayoutParams.FILL_PARENT);
		linearLayout.removeAllViews();
		linearLayout.setOrientation(LinearLayout.VERTICAL);
		if (null != answerlist && answerlist.size() > 0) {
			for (int i = 0; i < answerlist.size(); i++) {
				final QuestionAnswerBean answerBean = answerlist.get(i);
				// Log.v("qqqq", "select * from "
				// + SifTaskQuestionBean.TABLENAME + " where TaskQuestion_ID='"
				// + answerBean.getTaskQuestion_ID()+"'");
				questionBeans = questionDao.queryBySql("select * from "
						+ SifTaskQuestionBean.TABLENAME
						+ " where TaskQuestion_ID='"
						+ answerBean.getTaskQuestion_ID() + "'");
				if (null != questionBeans && questionBeans.size() > 0) {
					taskQuestionBean = questionBeans.get(0);
					showOpts(answerBean, taskQuestionBean);
				} else {
					getNetData(answerBean);
				}

			}
		} else {
			// 关联网络数据
			if (null != netAnswerList && netAnswerList.size() > 0) {
				for (int k = 0; k < netAnswerList.size(); k++) {
					final ViewAnswer answerBean = netAnswerList.get(k);
					gridView=new MyGridView(this, null);
					TextView textView = new TextView(this);
					// 改变默认的单行模式
					textView.setSingleLine(false);
					// 水平滚动设置为False
					textView.setHorizontallyScrolling(false);
					textView.setLayoutParams(params);
					textView.setTextSize(18);
					textView.setText(answerBean.getQuestionOrder() + "、"
							+ answerBean.getQuestion());
					linearLayout.addView(textView);

					// 选择或文字题
					if ("1".equals(answerBean.getQuestionType())
							|| "2".equals(answerBean.getQuestionType())
							|| "6".equals(answerBean.getQuestionType())) {
						textView = new TextView(this);
						// 改变默认的单行模式
						textView.setSingleLine(false);
						// 水平滚动设置为False
						textView.setHorizontallyScrolling(false);
						textView.setLayoutParams(params);
						textView.setTextSize(18);
						textView.setText((null == answerBean.getAnswer() || ""
								.equals(answerBean.getAnswer())) ? answerBean
								.getOtherAnswer() : answerBean.getAnswer());
						linearLayout.addView(textView);
					}
					// 图片题
					if ("3".equals(answerBean.getQuestionType())) {
						if (null != answerBean.getAVIList()
								&& answerBean.getAVIList().size() > 0) {
							lstImageItem = new ArrayList<HashMap<String, Object>>();
							linearLayout.setLayoutParams(params);
							gridView.setNumColumns(4);
							gridView.setVerticalSpacing(20);
							gridView.setLayoutParams(params);

							for (int j = 0; j < answerBean.getAVIList().size(); j++) {
								AVI avi = answerBean.getAVIList().get(j);
								// 根据照片的位置获取图片
								// Bitmap bitmap = getBitmap(avi.getURL());
								String temp = avi.getURL();
								String[] images = new String[answerBean
										.getAVIList().size() - 1];
								if (avi.getURL().indexOf("#") > -1) {
									images = avi.getURL().split("#");
									temp = images[j];
								}
								String tempImg = temp;

								// ImageView imageView = new ImageView(this);
								// imageView.setLayoutParams(relativeparams);
								// imageView.setPadding(20, 0, 20, 0);
								// imageView
								// .setScaleType(ImageView.ScaleType.FIT_XY);
								// // imageView.setImageBitmap(bitmap);
								// FinalBitmap finalBitmap = new FinalBitmap(
								// QuestionDetailActivity.this).init();
								// if(avi.getURL().indexOf("#")>-1){
								// finalBitmap.display(
								// imageView,
								// ConstansJsonUrl.BASEURL + "/"
								// + images[j]);
								// }else{
								// finalBitmap.display(
								// imageView,
								// ConstansJsonUrl.BASEURL + "/"
								// + avi.getURL());
								// }
								//
								// imageView.setOnClickListener(new
								// OnClickListener() {
								// @Override
								// public void onClick(View arg0) {
								// Intent intent=new
								// Intent(QuestionDetailActivity.this,
								// FullscreenShowActivity.class);
								// intent.putExtra("images", tempImg);
								// intent.putExtra("type", "1");
								// QuestionDetailActivity.this.startActivity(intent);
								// }
								// });
								// liLayout.addView(imageView);
								// flowLayout.addView(relativeLayout);
								tempImg = ConstansJsonUrl.BASEURL + "/"
										+ avi.getURL();
								HashMap<String, Object> hashMap = new HashMap<String, Object>();
								hashMap.put("ItemImage", tempImg);
								hashMap.put("ItemText", tempImg);
								lstImageItem.add(hashMap);
							}
							SimpleAdapter saImageItems = new SimpleAdapter(
									this, // 没什么解释
									lstImageItem,// 数据来源
									R.layout.night_item,// night_item的XML实现
									// 动态数组与ImageItem对应的子项
									new String[] { "ItemImage", "ItemText" },
									new int[] { R.id.ItemImage, R.id.ItemText }) {
								@Override
								public void setViewImage(final ImageView v,
										final String value) {
									// TODO Auto-generated method stub
									if (v.getId() == R.id.ItemImage) {
										FinalBitmap finalBitmap = new FinalBitmap(
												QuestionDetailActivity.this)
												.init();
										finalBitmap.display(v, value);
									} else {
										super.setViewImage(v, value);
									}
								}

							};
							netType="1";
							gridView.setAdapter(saImageItems);
							gridView.setOnItemClickListener(new ItemClickListener());
							linearLayout.addView(gridView);
						}
					}
					// 音频题
					if ("4".equals(answerBean.getQuestionType())) {
						if (null != answerBean.getAnswer()
								&& !"".equals(answerBean.getAnswer())) {
							RelativeLayout relativeLayout = new RelativeLayout(
									this);
							Display mDisplay = getWindowManager()
									.getDefaultDisplay();
							int W = mDisplay.getWidth();
							RelativeLayout.LayoutParams relativeparams = new RelativeLayout.LayoutParams(
									W / 4, W / 4);
							relativeparams
									.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
							relativeLayout.setLayoutParams(relativeparams);
							ImageView imageView = new ImageView(this);
							imageView.setLayoutParams(params);
							imageView.setPadding(20, 0, 20, 0);
							imageView.setScaleType(ImageView.ScaleType.FIT_XY);
							imageView
									.setBackgroundResource(R.drawable.audio_icon);
							imageView.setOnClickListener(new OnClickListener() {
								@Override
								public void onClick(View arg0) {
									try {
										// player = new MediaPlayer();
										// Log.v("qqqq", new
										// File(answerBean.getAnswer()).getAbsolutePath());
//										if(!playflag){
//											playflag=true;
											if(player.isPlaying()){
												player.stop();
												player.release();
											}
											player.setDataSource(answerBean
													.getAnswer());
											player.prepare();
											player.start();
											// btnplay.setEnabled(false);
											player.setOnCompletionListener(new OnCompletionListener() {
												@Override
												public void onCompletion(
														MediaPlayer mp) {
													player.release();
													// btnplay.setEnabled(true);
//													playflag=false;
												}
											});
//										}
										

									} catch (Exception e) {
										// TODO Auto-generated catch block
										e.printStackTrace();
									}
								}
							});
							relativeLayout.addView(imageView);
							linearLayout.addView(relativeLayout);
						} else {
							textView = new TextView(this);
							textView.setLayoutParams(params);
							textView.setTextSize(18);
							textView.setText("无音频数据");
							linearLayout.addView(textView);
						}
					}
					// 视频题
					if ("5".equals(answerBean.getQuestionType())) {
						if (null != answerBean.getAnswer()
								&& !"".equals(answerBean.getAnswer())) {
							RelativeLayout relativeLayout = new RelativeLayout(
									this);
							Display mDisplay = getWindowManager()
									.getDefaultDisplay();
							int W = mDisplay.getWidth();
							RelativeLayout.LayoutParams relativeparams = new RelativeLayout.LayoutParams(
									W / 4, W / 4);
							relativeparams
									.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
							relativeLayout.setLayoutParams(relativeparams);
							ImageView imageView = new ImageView(this);
							imageView.setLayoutParams(params);
							imageView.setPadding(20, 0, 20, 0);
							imageView.setScaleType(ImageView.ScaleType.FIT_XY);
							imageView
									.setBackgroundResource(R.drawable.video_icon);
							imageView.setOnClickListener(new OnClickListener() {
								@Override
								public void onClick(View arg0) {
									Intent intent = new Intent(
											Intent.ACTION_VIEW);
									String type = "video/mp4";
									Uri uri = Uri.fromFile(new File(answerBean
											.getAnswer()));
									intent.setDataAndType(uri, type);
									startActivity(intent);

								}
							});
							relativeLayout.addView(imageView);
							linearLayout.addView(relativeLayout);
						} else {
							textView = new TextView(this);
							textView.setLayoutParams(params);
							textView.setTextSize(18);
							textView.setText("无视频数据");
							linearLayout.addView(textView);
						}
					}

				}
				linearLayout.setPadding(0, 10, 0, 100);
			}
		}
	}

	private Uri getImageUri(String path) {

		return Uri.fromFile(new File(path));
	}

	private Bitmap getBitmap(String path) {

		Uri uri = getImageUri(path);
		InputStream in = null;
		try {
			in = mContentResolver.openInputStream(uri);

			// Decode image size
			BitmapFactory.Options o = new BitmapFactory.Options();
			o.inJustDecodeBounds = true;

			BitmapFactory.decodeStream(in, null, o);
			in.close();

			int scale = 1;
			if (o.outHeight > IMAGE_MAX_SIZE || o.outWidth > IMAGE_MAX_SIZE) {
				scale = (int) Math.pow(
						2,
						(int) Math.round(Math.log(IMAGE_MAX_SIZE
								/ (double) Math.max(o.outHeight, o.outWidth))
								/ Math.log(0.5)));
			}

			BitmapFactory.Options o2 = new BitmapFactory.Options();
			o2.inSampleSize = scale;
			in = mContentResolver.openInputStream(uri);
			Bitmap b = BitmapFactory.decodeStream(in, null, o2);
			if(null!=b){
				b = comp(b, 1280f, 720f, path);
			}
			in.close();

			return b;
		} catch (FileNotFoundException e) {
			 Log.e("qqqq", "file " + path + " not found");
		} catch (IOException e) {
			 Log.e("qqqq", "file " + path + " not found");
		}
		return null;
	}

	// 压缩图片分辨率
	private Bitmap comp(Bitmap image, float hh, float ww, String path) {

		ByteArrayOutputStream baos = new ByteArrayOutputStream();

		image.compress(Bitmap.CompressFormat.JPEG, 100, baos);
		if (baos.toByteArray().length / 1024 > 1024) {// 判断如果图片大于1M,进行压缩避免在生成图片（BitmapFactory.decodeStream）时溢出
			baos.reset();// 重置baos即清空baos
			image.compress(Bitmap.CompressFormat.JPEG, 50, baos);// 这里压缩50%，把压缩后的数据存放到baos中
		}
		ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());
		BitmapFactory.Options newOpts = new BitmapFactory.Options();
		// 开始读入图片，此时把options.inJustDecodeBounds 设回true了
		newOpts.inJustDecodeBounds = true;
		Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, newOpts);
		newOpts.inJustDecodeBounds = false;
		int w = newOpts.outWidth;
		int h = newOpts.outHeight;
		// 现在主流手机比较多是800*480分辨率，所以高和宽我们设置为
		// float hh = 800f;//这里设置高度为800f
		// float ww = 480f;//这里设置宽度为480f
		// 缩放比。由于是固定比例缩放，只用高或者宽其中一个数据进行计算即可
		int be = 1;// be=1表示不缩放
		if (w > h && w > ww) {// 如果宽度大的话根据宽度固定大小缩放
			be = (int) (newOpts.outWidth / ww);
		} else if (w < h && h > hh) {// 如果高度高的话根据宽度固定大小缩放
			be = (int) (newOpts.outHeight / hh);
		}
		if (be <= 0)
			be = 1;
		newOpts.inSampleSize = be;// 设置缩放比例
		// 重新读入图片，注意此时已经把options.inJustDecodeBounds 设回false了
		isBm = new ByteArrayInputStream(baos.toByteArray());
		bitmap = BitmapFactory.decodeStream(isBm, null, newOpts);
		return compressImage(bitmap, path);// 压缩好比例大小后再进行质量压缩
	}

	// 图片质量压缩
	private Bitmap compressImage(Bitmap image, String path) {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		image.compress(Bitmap.CompressFormat.JPEG, 100, baos);// 质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
		int options = 100;
		while (baos.toByteArray().length / 1024 > 100) { // 循环判断如果压缩后图片是否大于100kb,大于继续压缩
			baos.reset();// 重置baos即清空baos
			image.compress(Bitmap.CompressFormat.JPEG, options, baos);// 这里压缩options%，把压缩后的数据存放到baos中
			options -= 10;// 每次都减少10
		}
		ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());// 把压缩后的数据baos存放到ByteArrayInputStream中
		Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);// 把ByteArrayInputStream数据生成图片

		File f = new File(path);
		if (f.exists()) {
			f.delete();
		}
		try {
			FileOutputStream out = new FileOutputStream(f);
			bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
			out.flush();
			out.close();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return bitmap;
	}

	void showOpts(final QuestionAnswerBean answerBean,
			SifTaskQuestionBean taskQuestionBean) {
		linearLayout.setOrientation(LinearLayout.VERTICAL);
		LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
				LinearLayout.LayoutParams.FILL_PARENT,
				LinearLayout.LayoutParams.WRAP_CONTENT);
		TextView textView = new TextView(this);
		// 改变默认的单行模式
		textView.setSingleLine(false);
		// 水平滚动设置为False
		textView.setHorizontallyScrolling(false);
		textView.setLayoutParams(params);
		textView.setTextSize(18);
		textView.setText(taskQuestionBean.getOrderIndex() + "、"
				+ taskQuestionBean.getQuestion());
		linearLayout.addView(textView);

		// 选择或文字题
		if ("1".equals(taskQuestionBean.getQuestionType())
				|| "2".equals(taskQuestionBean.getQuestionType())
				|| "6".equals(taskQuestionBean.getQuestionType())) {
			textView = new TextView(this);
			// 改变默认的单行模式
			textView.setSingleLine(false);
			// 水平滚动设置为False
			textView.setHorizontallyScrolling(false);
			textView.setLayoutParams(params);
			textView.setTextSize(18);
			textView.setText((null == answerBean.getAnswer() || ""
					.equals(answerBean.getAnswer())) ? answerBean
					.getOtherAnswer() : answerBean.getAnswer());
			linearLayout.addView(textView);
		}
		// 图片题
		if ("3".equals(taskQuestionBean.getQuestionType())) {
			if (null != answerBean.getFileCount()
					&& !"".equals(answerBean.getFileCount())) {
				// FlowLayout flowLayout=new FlowLayout(this);
				// if("1".equals(type)){
				// LinearLayout liLayout = new LinearLayout(this);
				// Display mDisplay = getWindowManager().getDefaultDisplay();
				// int W = mDisplay.getWidth();
				// LinearLayout.LayoutParams relativeparams = new
				// LinearLayout.LayoutParams(
				// W / 4, W / 4);
				// // relativeparams.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
				// liLayout.setOrientation(LinearLayout.HORIZONTAL);
				// liLayout.setLayoutParams(params);
				lstImageItem = new ArrayList<HashMap<String, Object>>();
				linearLayout.setLayoutParams(params);
				gridView = new MyGridView(this, null);
				gridView.setNumColumns(4);
				gridView.setVerticalSpacing(20);
				gridView.setLayoutParams(params);
				for (int j = 0; j < Integer.valueOf(answerBean.getFileCount()); j++) {
					// 根据照片的位置获取图片
					String[] imgs = answerBean.getAnswer().split("#");
					final String tempImg = imgs[j];
					// Bitmap bitmap = getBitmap(imgs[j]);
					// ImageView imageView = new ImageView(this);
					// imageView.setLayoutParams(relativeparams);
					// imageView.setPadding(20, 0, 20, 0);
					// imageView.setScaleType(ImageView.ScaleType.FIT_XY);
					// imageView.setImageBitmap(bitmap);
					// imageView.setOnClickListener(new OnClickListener() {
					// @Override
					// public void onClick(View arg0) {
					// Intent intent=new Intent(QuestionDetailActivity.this,
					// FullscreenShowActivity.class);
					// intent.putExtra("images", tempImg);
					// intent.putExtra("type", "0");
					// QuestionDetailActivity.this.startActivity(intent);
					// }
					// });
					// liLayout.addView(imageView);
					// flowLayout.addView(relativeLayout);
					Log.v("qqqq", imgs[j]);
					getBitmap(imgs[j]);
					HashMap<String, Object> hashMap = new HashMap<String, Object>();
					hashMap.put("ItemImage", tempImg);
					hashMap.put("ItemText", tempImg);
					lstImageItem.add(hashMap);
				}
				SimpleAdapter saImageItems = new SimpleAdapter(this, // 没什么解释
						lstImageItem,// 数据来源
						R.layout.night_item,// night_item的XML实现
						// 动态数组与ImageItem对应的子项
						new String[] { "ItemImage", "ItemText" }, new int[] {
								R.id.ItemImage, R.id.ItemText });
				netType="0";
				gridView.setAdapter(saImageItems);
				gridView.setOnItemClickListener(new ItemClickListener());
				linearLayout.addView(gridView);
				// linearLayout.addView(liLayout);
				// }
			}
		}
		// 音频题
		if ("4".equals(taskQuestionBean.getQuestionType())) {
			if (null != answerBean.getAnswer()
					&& !"".equals(answerBean.getAnswer())) {
				RelativeLayout relativeLayout = new RelativeLayout(this);
				Display mDisplay = getWindowManager().getDefaultDisplay();
				int W = mDisplay.getWidth();
				RelativeLayout.LayoutParams relativeparams = new RelativeLayout.LayoutParams(
						W / 4, W / 4);
				relativeparams.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
				relativeLayout.setLayoutParams(relativeparams);
				ImageView imageView = new ImageView(this);
				imageView.setLayoutParams(params);
				imageView.setPadding(20, 0, 20, 0);
				imageView.setScaleType(ImageView.ScaleType.FIT_XY);
				imageView.setBackgroundResource(R.drawable.audio_icon);
				imageView.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View arg0) {
						try {
							// Log.v("qqqq", new
							// File(answerBean.getAnswer()).getAbsolutePath());
							if(player.isPlaying()){
								player.stop();
								player.release();
							}
							player.setDataSource(answerBean.getAnswer());
							player.prepare();
							player.start();
							// btnplay.setEnabled(false);
							player.setOnCompletionListener(new OnCompletionListener() {
								@Override
								public void onCompletion(MediaPlayer mp) {
									player.release();
									// btnplay.setEnabled(true);
								}
							});

						} catch (Exception e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				});
				relativeLayout.addView(imageView);
				linearLayout.addView(relativeLayout);
			} else {
				textView = new TextView(this);
				textView.setLayoutParams(params);
				textView.setTextSize(18);
				textView.setText("无音频数据");
				linearLayout.addView(textView);
			}
		}
		// 视频题
		if ("5".equals(taskQuestionBean.getQuestionType())) {
			if (null != answerBean.getAnswer()
					&& !"".equals(answerBean.getAnswer())) {
				RelativeLayout relativeLayout = new RelativeLayout(this);
				Display mDisplay = getWindowManager().getDefaultDisplay();
				int W = mDisplay.getWidth();
				RelativeLayout.LayoutParams relativeparams = new RelativeLayout.LayoutParams(
						W / 4, W / 4);
				relativeparams.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
				relativeLayout.setLayoutParams(relativeparams);
				ImageView imageView = new ImageView(this);
				imageView.setLayoutParams(params);
				imageView.setPadding(20, 0, 20, 0);
				imageView.setScaleType(ImageView.ScaleType.FIT_XY);
				imageView.setBackgroundResource(R.drawable.video_icon);
				imageView.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View arg0) {
						Intent intent = new Intent(Intent.ACTION_VIEW);
						String type = "video/mp4";
						Uri uri = Uri.fromFile(new File(answerBean.getAnswer()));
						intent.setDataAndType(uri, type);
						startActivity(intent);

					}
				});
				relativeLayout.addView(imageView);
				linearLayout.addView(relativeLayout);
			} else {
				textView = new TextView(this);
				textView.setLayoutParams(params);
				textView.setTextSize(18);
				textView.setText("无视频数据");
				linearLayout.addView(textView);
			}
		}
		linearLayout.setPadding(0, 0, 0, 100);
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	void getNetData(final QuestionAnswerBean answerBean) {
		FinalHttp fh = new FinalHttp();
		AjaxParams params = new AjaxParams();
		params.put("sid", ConstansJsonUrl.viewQuestion_url);
		params.put("did", SinofaithUtil.did);
		params.put("answerid", Answer_ID);
		Log.v("qqqq", ConstansJsonUrl.REQUEST_URL + params);
		fh.get(ConstansJsonUrl.REQUEST_URL, params, new AjaxCallBack() {

			@Override
			public void onStart() {
				super.onStart();
			}

			@Override
			public void onLoading(long count, long current) {
				// TODO Auto-generated method stub
				super.onLoading(count, current);
			}

			@Override
			public void onSuccess(Object t) {
				// TODO Auto-generated method stub
				super.onSuccess(t);
				Log.v("qqqq", t.toString());
				try {
					ViewQuestionBean viewQuestionBean = HttpJsonAdapter
							.getInstance().get(t.toString(),
									ViewQuestionBean.class);
					if (viewQuestionBean.getResult().equals("0")) {

						if (null != viewQuestionBean.getQuestionList()
								&& viewQuestionBean.getQuestionList().size() > 0) {

							ArrayList<Question> questions = viewQuestionBean
									.getQuestionList();
							questionBeans = new ArrayList<SifTaskQuestionBean>();
							if (null != questions && questions.size() > 0) {
								for (int i = 0; i < questions.size(); i++) {
									Question question = questions.get(i);
									taskQuestionBean = new SifTaskQuestionBean();
									taskQuestionBean
											.setTaskQuestion_ID(question
													.getTaskQuestion_ID());
									taskQuestionBean.setTemplate_ID(question
											.getTemplate_ID());
									taskQuestionBean.setQuestion(question
											.getQuestion());
									taskQuestionBean.setQuestionType(question
											.getQuestionType());
									taskQuestionBean.setHasOtherOption(question
											.getHasOtherOption());
									taskQuestionBean.setOrderIndex(question
											.getOrderIndex());
									taskQuestionBean.setIsRequired(question
											.getIsRequired());
									taskQuestionBean.setPhotoNum(question
											.getPhotoNum());
									taskQuestionBean.setPhotoMode(question
											.getPhotoMode());
									taskQuestionBean.setPhotoDesc(question
											.getPhotoDesc());
									taskQuestionBean.setZaikuFlag(question
											.getZaikuFlag());
									// questionBeans.add(taskQuestionBean);

									if (answerBean.getTaskQuestion_ID().equals(
											question.getTaskQuestion_ID())) {
										showOpts(answerBean, taskQuestionBean);
									}

								}

							}
						}

					} else {
						Toast.makeText(QuestionDetailActivity.this,
								viewQuestionBean.getDesc(), Toast.LENGTH_LONG)
								.show();
						QuestionDetailActivity.this.finish();
					}
				} catch (Exception e) {
					Toast.makeText(QuestionDetailActivity.this, e.getMessage(),
							Toast.LENGTH_LONG).show();
					QuestionDetailActivity.this.finish();
				}

			}

			@Override
			public void onFailure(Throwable t, int errorNo, String strMsg) {
				// TODO Auto-generated method stub
				super.onFailure(t, errorNo, strMsg);
				Toast.makeText(QuestionDetailActivity.this, strMsg,
						Toast.LENGTH_LONG).show();
			}

		});
	}

	class ItemClickListener implements OnItemClickListener {
		public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
				long arg3) {
			// 在本例中arg2=arg3
			HashMap<String, Object> item = (HashMap<String, Object>) arg0
					.getItemAtPosition(arg2);
			// 显示所选Item的ItemText
			if (!"button".equals((String) item.get("ItemText"))) {
				Intent intent = new Intent(QuestionDetailActivity.this,
						FullscreenShowActivity.class);
				intent.putExtra("images", (String) item.get("ItemText"));
				intent.putExtra("type", netType);
				QuestionDetailActivity.this.startActivity(intent);
			}
		}
	}
	
	private String getSPString(){
		SharedPreferences sp=this.getSharedPreferences("login", Context.MODE_PRIVATE);
		return sp.getString("UserMobile", "");
	}
}
